##########################################
## Copyright 2012-2013 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

import urllib.request as url

try:
    from lxml import etree
except ImportError:
    import xml.etree.ElementTree as etree


class XmlWriter:

    tag = {
           'medialist': 0,
           'program': 1,
           'plugins': 2
           }

    def __init__(self, file):
        self.file = file
        self.root = etree.Element('{LiSP}list')
        self.root.append(etree.Element('medialist'))
        self.root.append(etree.Element('program'))
        self.root.append(etree.Element('plugins'))

    def appendMedia(self, conf):
        media = etree.Element('media')
        for opt in conf:
            media.append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))
        self.root[self.tag['medialist']].append(media)

    def appendPluginSettings(self, plugin, conf):
        plugin = etree.Element('plugin', attrib={'name': plugin})
        for opt in conf:
            plugin.append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))
        self.root[self.tag['plugins']].append(plugin)

    def appendProgramSettings(self, conf):
        for opt in conf:
            self.root[self.tag['program']].append(etree.Element('option', attrib={'name': opt, 'value': url.pathname2url(str(self.format(conf[opt])))}))

    def writeFile(self):
        with open(self.file, mode='w', encoding='utf-8') as a_file:
            a_file.write(str(etree.tostring(self.root, pretty_print=True)).replace('ns0:', '').replace(':ns0', '').replace('\\\'', '\'').replace('b\'<', '<').replace('n\'', 'n').replace('\\n', '\n'))

    def format(self, obj):
        if(isinstance(obj, str)):
            obj = '\"' + obj + '\"'
        return obj
